﻿using System.Text;

// 注册编码库

Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

string str = "我是中国人";
string msg1 = "";
string msg2 = "";

Encoding utf8 = Encoding.UTF8;
Encoding gb2312 = Encoding.GetEncoding("GB2312");

// 转换为 UTF8 编码方式
byte[] bytes1 = utf8.GetBytes(str);
msg1 = utf8.GetString(bytes1);

// 转换为 GB2312 编码方式
byte[] bytes2 = gb2312.GetBytes(str);
msg2 = gb2312.GetString(bytes2);

Console.WriteLine(str);
Console.WriteLine(msg1);
Console.WriteLine(msg2);

Console.WriteLine("------");


string source = @"d:\\1.txt";
string target = @"d:\\new.txt";

// 读取文件流
FileStream fsRead = new FileStream(source, FileMode.Open, FileAccess.Read);

// 写入流
FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write);

byte[] buffer = new byte[1024 * 1024 * 5];
while (true)
{
    // 返回读取字节数
    int r = fsRead.Read(buffer, 0, buffer.Length);
    if (r == 0)
    {
        break;
    }

    // 写入
    fsWrite.Write(buffer, 0, r);
}

fsRead.Close();
fsWrite.Close();
fsRead.Dispose();
fsWrite.Dispose();

Console.WriteLine("------");

string[] names = { "tom", "jack", "jerry" };
using (StreamWriter sw = new StreamWriter("d:/names.txt"))
{
    foreach (var name in names)
    {
        sw.WriteLine(name);
    }
}

try
{
    // 创建一个StreamReader的实例来读取文件
    using (StreamReader sr = new StreamReader("d:/names.txt", Encoding.UTF8))
    {
        string line;
        // 从文件读取并显示行，直到文件的末尾
        while ((line = sr.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}
catch (Exception e)
{
    // 向用户显示出错消息
    Console.WriteLine("The file could not be read");
    Console.WriteLine(e.Message);
}

Console.WriteLine("------");

BinaryWriter bw;
BinaryReader br;

int i = 24;
double d = 23234.1111;
bool b = true;
string s = "I am sorry";
// 创建文件
bw = new BinaryWriter(new FileStream("mydata.txt", FileMode.Create));

// 写入文件
bw.Write(i);
bw.Write(d);
bw.Write(b);
bw.Write(s);
bw.Close();
bw.Dispose();

// 读取文件
br = new BinaryReader(new FileStream("mydata.txt", FileMode.Open));
i = br.ReadInt32();
Console.WriteLine($"Int data:{i}");
d = br.ReadDouble();
Console.WriteLine($"Double data:{0}");
b = br.ReadBoolean();
Console.WriteLine($"Boolean data:{0}");
s = br.ReadString();
Console.WriteLine($"String data:{0}");

br.Close();
br.Dispose();

Console.ReadLine();